import { conn } from '../../@beshell/conn-ts/Connection';
import { AppModel } from '../../../../model/AppModel';
import { createUIWidgetMenu } from '../BlockPackage'

export default {

    category: Blockly.Categories.event ,
    
    color: [
        Blockly.Colours.operators.primary,
        Blockly.Colours.operators.secondary,
        Blockly.Colours.operators.tertiary
    ] ,

    previousStatement: false ,
    nextStatement: true ,
    hat: true ,
    
    eventHandle: true ,

    init(model: AppModel) {
        this.appendDummyInput()
                .appendField("当UI按钮")
                .appendField(createUIWidgetMenu(model, "Button"), 'uibutton')
                .appendField(new Blockly.FieldDropdown(() => {
                    return [
                        ['按下' , 'down'] ,
                        ['释放' , 'up'] ,
                    ]
                }), 'event')
    } ,

    run (args: any, util: any, runtime: any, model: AppModel) {
        if(!conn.isConnected) {
            return
        }

        let widget = model.ui.mapWidgets[args.uibutton]
        if(!widget)
            return true

        // 向远程零件转发
        conn.console.run(`be.bus.emit("ui-event.${widget.name}.${args.event}")`)

        return true
    } ,

    coder: {
        JavaScript(block: any, coder: any, model: AppModel) {

            let event = block.getFieldValue('event')
            let wid = block.getFieldValue('uibutton')
            let widget = model.ui.mapWidgets[wid]
            if(!widget)
                return ''
            
            let inner = ''
            let nextBlock = block.nextConnection && block.nextConnection.targetBlock()
            if(nextBlock) {
                coder.indent ++
                inner = coder.blockToCode(nextBlock)
                coder.indent --
            }

            return `${coder.indentString()}be.bus.on( "ui-event.${widget.name}.${event}", async ()=>{\n`
            + inner + '\n'
            + `${coder.indentString()}})\n`
        }
    }
}
